package com.leon.ikun.utils;

import android.content.Context;
import android.content.pm.PackageManager;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.leon.ikun.beans.home.HomeRecommendApp;
import com.leon.ikun.beans.publicBeans.resources.video.VideoDetail;
import com.leon.ikun.http.ApiHelper;
import com.leon.ikun.http.BaseUrl;
import com.leon.ikun.http.HttpApi;
import com.leon.ikun.http.RetrofitClient;
import com.leon.ikun.ui.dialogs.TipDialog;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author Leon
 * @Time 2023/02/28
 * @Desc
 */
public class Utils {
    public static void CheckUpdate(Context context, boolean showToast) {
        HttpApi.ApiGet httpApi = new RetrofitClient(BaseUrl.CONFIG, context).ApiGet();
        new ApiHelper<>(httpApi.getConfig()).setOnResult(config -> {

            try {
                int nowVersionCode = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode;

                // 将反代理baseurl保存至preference
                PreferenceUtils.setProxy(context, config.getProxy().getUrl());

                if (config.getVersion().getVersionCode() > nowVersionCode) {
                    TipDialog.ShowUpdateDialog(context, config);
                } else if (showToast) {
                    Toast.makeText(context, "当前版本为最新版本", Toast.LENGTH_SHORT).show();
                }
            } catch (PackageManager.NameNotFoundException e) {
                throw new RuntimeException(e);
            }
        }).doIt();
    }

    @NonNull
    public static List<VideoDetail.Data.View.Page> getPages(HomeRecommendApp.VodInfo data) {
        String[] parts = data.getVodPlayUrl().split("\\$\\$\\$")[1].split("#");
        List<VideoDetail.Data.View.Page> list = new ArrayList<>();

        for (String part : parts) {
            String[] splitPart = part.split("\\$");
            if (splitPart.length == 2 && splitPart[1].endsWith(".m3u8")) {
                String episode = splitPart[0];
                String link = splitPart[1];
                VideoDetail.Data.View.Page.Dimension dimension = new VideoDetail.Data.View.Page.Dimension(1080,0,1920);
                VideoDetail.Data.View.Page page = new VideoDetail.Data.View.Page(data.getVodId(), dimension, 0, data.getVodPic(), "vupload", 1, episode, "", link, new VideoDetail.Data.View.Page.ItemState(0,true));
                list.add(page);
            }
        }
        return list;
    }
}
